<template>
  <div id="addMoviePage">
    <h2 style="margin-bottom: 32px" v-if="!props.id">创建影院</h2>
    <h2 style="margin-bottom: 32px" v-else>编辑影院</h2>
    <el-form
      :model="form"
      :style="{ width: '480px', margin: '0 auto' }"
      label-align="left"
      auto-label-width
    >
      <el-form-item field="theaterName" label="影院名称">
        <el-input v-model="form.theaterName" placeholder="请输入影院名称" />
      </el-form-item>
      <el-form-item field="theaterAddress" label="影院地址">
        <el-input v-model="form.theaterAddress" placeholder="请输入影院地址" />
      </el-form-item>
      <el-form-item field="theaterIcon" label="电影图标">
        <el-input v-model="form.theaterIcon" placeholder="请输入影院图标" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" style="width: 120px"
          >提交
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watchEffect } from "vue";
import API from "@/api";
import { useLoginUserStore } from "@/store/userStore";
import { useRouter } from "vue-router";
import { withDefaults, defineProps } from "vue";

import { ElMessage } from "element-plus";
import { MOVIE_TYPE_MAP } from "@/constant/movie";
import {
  addTheaterUsingPost,
  getTheaterVoByIdUsingGet,
  updateTheaterUsingPost,
} from "@/api/theaterController";

const loginUserStore = useLoginUserStore();
const router = useRouter();

interface Props {
  id: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: () => {
    return "";
  },
});

const old = ref<API.TheaterVO>();

const form = ref({
  theaterName: "",
  theaterAddress: "",
  theaterIcon: "",
} as API.TheaterQueryRequest);

/**
 * 加载数据
 */
const loadData = async () => {
  if (!props.id) {
    return;
  }
  const res = await getTheaterVoByIdUsingGet({
    id: props.id as any,
  });
  if (res.data.code === 0 && res.data.data) {
    old.value = res.data.data as any;
    form.value = res.data.data;
  } else {
    ElMessage({
      message: "获取数据失败，" + res.data.message,
      type: "error",
    });
  }
};

watchEffect(() => {
  loadData();
});

const handleSubmit = async () => {
  let res: any;
  //判断是否是更新操作
  if (props.id) {
    res = await updateTheaterUsingPost({
      id: props.id as any,
      ...form.value,
    });
  } else {
    res = await addTheaterUsingPost(form.value);
  }

  if (res.data.code === 0) {
    ElMessage({
      message: "操作成功",
      type: "success",
    });
    setTimeout(() => {
      router.push(`/`);
    }, 3000);
  } else {
    ElMessage({
      message: "操作失败，" + res.data.message,
      type: "error",
    });
  }
};
</script>
